package com.sanpu.kxe.business.trade.view;

import android.content.Context;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.dialogplus.OnItemClickListener;
import com.sanpu.kxe.R;
import com.sanpu.kxe.base.BaseTitleActivity;
import com.sanpu.kxe.business.card.bean.BankInfoOutput;
import com.sanpu.kxe.business.card.provider.ICardProvider;
import com.sanpu.kxe.business.trade.adapter.ChooseBankAdapter;
import com.sanpu.kxe.business.trade.adapter.SupportBankAdapter;
import com.sanpu.kxe.business.trade.bean.SupportBankOutput;
import com.sanpu.kxe.business.trade.contract.QuickPayWebContract;
import com.sanpu.kxe.business.trade.contract.TradeConfig;
import com.sanpu.kxe.business.trade.presenter.QuickPayWebPresenter;
import com.sanpu.kxe.common.enums.PayType;
import com.sanpu.kxe.common.interfaces.DialogViewListener;
import com.sanpu.kxe.common.interfaces.UrlConstants;
import com.sanpu.kxe.common.view.NoScrollListView;
import com.sanpu.kxe.jump.eventbus.RefreshBankEvent;
import com.sanpu.kxe.jump.imageloader.JKImageLoader;
import com.sanpu.kxe.module.immersionbar.ImmersionBar;
import com.sanpu.kxe.module.roundview.RoundTextView;
import com.sanpu.kxe.utils.DialogUtil;
import com.sanpu.kxe.utils.PublicProviderUtil;
import com.sanpu.kxe.utils.SystemBarHelper;
import com.sanpu.kxe.utils.ToastUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Description：快捷H5收款
 * Created by 薛勇军 on 2019/3/4.
 */

public class QuickPayWebActivity extends BaseTitleActivity implements QuickPayWebContract.View {

    @Bind(R.id.scrollView)
    ScrollView scrollView;
    @Bind(R.id.tvTitle)
    TextView tvTitle;
    @Bind(R.id.arrivalAmountTv)
    TextView vArrivalAmountTv;
    @Bind(R.id.payment_amount)
    TextView vPaymentAmount;
    @Bind(R.id.out_icon)
    ImageView vOutIcon;
    @Bind(R.id.out_bank_name)
    TextView vOutBankName;
    @Bind(R.id.out_select_bank)
    LinearLayout vOutSelectBank;
    @Bind(R.id.in_icon)
    ImageView vInIcon;
    @Bind(R.id.in_bank_name)
    TextView vInBankName;
    @Bind(R.id.in_select_bank)
    LinearLayout vInSelectBank;
    @Bind(R.id.comfirmRtv)
    RoundTextView comfirmRtv;
    @Bind(R.id.remarkTv)
    TextView remarkTv;

    @Bind(R.id.supportBankLv)
    NoScrollListView supportBankLv;
    @Bind(R.id.supportBankLl)
    LinearLayout supportBankLl;
    @Bind(R.id.headerView)
    RelativeLayout headerView;

    private ChooseBankAdapter mBankAdapter;
    private SupportBankAdapter mSupportBankAdapter;

    private QuickPayWebContract.Presenter mPresenter;

    private ArrayList<BankInfoOutput> mOutBankList = new ArrayList<>();
    private ArrayList<BankInfoOutput> mInBankList = new ArrayList<>();
    private String needPic;

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_quickpay_web;
    }

    @Override
    protected void initView() {
        super.initView();
        int barHeight = SystemBarHelper.getStatusBarHeight(getContext());
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) headerView.getLayoutParams();
        params.setMargins(0, barHeight, 0, 0);
        headerView.setLayoutParams(params);

        mBankAdapter = new ChooseBankAdapter(mContext, new ArrayList<BankInfoOutput>());
        mSupportBankAdapter = new SupportBankAdapter(new ArrayList<SupportBankOutput>(), mContext);
        supportBankLv.setAdapter(mSupportBankAdapter);

        try {
            PayType mType = (PayType) getIntent().getSerializableExtra("type");
            if (mType == PayType.T1QUICKPAY)
                tvTitle.setText("快捷封顶");
            else
                tvTitle.setText("快捷支付");
            String mPaymentAmt = getIntent().getStringExtra(TradeConfig.INTENT_REQAMOUNT);
            String rate = getIntent().getStringExtra(TradeConfig.INTENT_RATE);
            int stlType = getIntent().getIntExtra(TradeConfig.INTENT_STLTYPE, 0);
            String rlId = getIntent().getStringExtra(TradeConfig.INTENT_RLID);
            String maxFeeAmt = getIntent().getStringExtra(TradeConfig.INTENT_MAXFEEAMT);
            String otherFeeAmt = getIntent().getStringExtra(TradeConfig.INTENT_OTHERFEEAMT);
            needPic = getIntent().getStringExtra(TradeConfig.INTENT_NEEDPIC);
            if (!TextUtils.isEmpty(mPaymentAmt)) {
                vPaymentAmount.setText(new DecimalFormat("#0.00").format(Double.valueOf(mPaymentAmt)));
            }
            double needFee = Double.valueOf(mPaymentAmt) * Double.valueOf(rate) / 100;
            if (!TextUtils.isEmpty(maxFeeAmt)) {
                double maxFee = Double.parseDouble(maxFeeAmt);
                if (maxFee > 0 && maxFee < needFee) {
                    needFee = maxFee;
                }
            }
            double otherFee = 0.00;
            if (!TextUtils.isEmpty(otherFeeAmt)) {
                otherFee = Double.parseDouble(otherFeeAmt);
            }
            double arrivalAmount = Double.valueOf(mPaymentAmt) - needFee - otherFee;
            if (stlType == 1) {
                remarkTv.setText("勿需提现，T+1到账");
            } else {
                remarkTv.setText("勿需提现，即刷即到；每笔收取" + otherFee + "元/笔");
            }
            vArrivalAmountTv.setText(new DecimalFormat("#0.00").format(arrivalAmount));
            mType = (PayType) getIntent().getSerializableExtra(TradeConfig.INTENT_REQTYPE);

            mPresenter = new QuickPayWebPresenter(this);
            mPresenter.initData(needPic, rlId, mType.getValue(), mPaymentAmt);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClick({R.id.leftIv, R.id.rightTv, R.id.comfirmRtv, R.id.out_select_bank, R.id.in_select_bank})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.leftIv:
                finish();
                break;
            case R.id.rightTv:
                mPresenter.openBrowserX5Activity(UrlConstants.BANKS_LIMIT_HELP);
                break;
            case R.id.comfirmRtv:
                if (vOutBankName.getTag() == null) {
                    ToastUtil.showTextViewPrompt("请选择付款信用卡");
                    return;
                }
                if (vInBankName.getTag() == null) {
                    ToastUtil.showTextViewPrompt("请选择收款储蓄卡");
                    return;
                }
                mPresenter.openBrowserX5Activity(((BankInfoOutput) vOutBankName.getTag()).getBankId(),
                        ((BankInfoOutput) vInBankName.getTag()).getBankId());
                break;
            case R.id.out_select_bank:
                mBankAdapter.setCheckPosition(
                        vOutBankName.getTag() != null ? mOutBankList.lastIndexOf(vOutBankName.getTag()) : -1);
                mBankAdapter.setNotifyData(mOutBankList);
                bankDialog(true);
                break;
            case R.id.in_select_bank:
                DialogUtil.getInstance().dialogNoTitletTwoBtnHaveCallBack(mContext,
                        "变更收款卡须更改默认结算卡", "取消", "去更改",
                        new DialogViewListener() {
                            @Override
                            public void btnRightConfirm() {
                                ICardProvider provider = PublicProviderUtil.getProvider(ICardProvider.class);
                                if (provider != null) {
                                    provider.openMyBankListActivity(mContext);
                                }
                            }

                            @Override
                            public void btnLeftCancel() {

                            }
                        });
                break;
        }
    }

    /**
     * 提现银行卡对话框
     */
    private void bankDialog(final boolean isOutBank) {
        View header = LayoutInflater.from(mContext).inflate(R.layout.layout_choose_bank_header, null);
        final DialogPlus dialog = DialogPlus.newDialog(this)
                .setAdapter(mBankAdapter)
                .setHeader(header)
                .setFooter(R.layout.layout_choose_bank_foot)
                .setGravity(Gravity.CENTER)
                .setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(DialogPlus dialog, Object item, View view, int position) {
                        if (position < 0) return;
                        dialog.dismiss();
                        onDialogItemClickListener(isOutBank, position);
                    }
                })
                .setExpanded(false)
                .create();
        dialog.show();

        header.findViewById(R.id.arrow).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    /**
     * 选择银行卡列表点击事件处理
     */
    private void onDialogItemClickListener(boolean isOutBank, int position) {
        if ((isOutBank && mOutBankList.size() == position)
                || (!isOutBank && mInBankList.size() == position)) {
            ICardProvider provider = PublicProviderUtil.getProvider(ICardProvider.class);
            if (provider != null) {
                provider.openAddBankSetupActivity(mContext, false);
            }
            return;
        }
        try {
            BankInfoOutput checkBank;
            if (isOutBank) {
                checkBank = mOutBankList.get(position);
                showBankInfo(checkBank, true);
            } else {
                checkBank = mInBankList.get(position);
                showBankInfo(checkBank, false);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void showSupportBankView(List<SupportBankOutput> bankOutputs) {
        if (bankOutputs != null && bankOutputs.size() > 0) {
            supportBankLl.setVisibility(View.VISIBLE);
            mSupportBankAdapter.setNotifyData(bankOutputs);
            scrollView.scrollTo(0, 0);
        } else {
            supportBankLl.setVisibility(View.GONE);
        }
    }

    @Override
    public void showBankInfo(BankInfoOutput infoOutput, boolean isOutBank) {
        try {
            JKImageLoader.getInstance().displayImage(mContext,
                    UrlConstants.getBaseUrl() + infoOutput.getLogoPath(), isOutBank ? vOutIcon : vInIcon);
            String bankNo = infoOutput.getBankNo();
            (isOutBank ? vOutBankName : vInBankName).setText(infoOutput.getBankName().replace(" ", "")
                    + "  (" + bankNo.substring(bankNo.length() - 4, bankNo.length()) + ")");
            (isOutBank ? vOutBankName : vInBankName).setTag(infoOutput);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void setBankListData(List<BankInfoOutput> outBankList, List<BankInfoOutput> inBankList) {
        mOutBankList.clear();
        mInBankList.clear();
        if (outBankList != null) {
            mOutBankList.addAll(outBankList);
        }
        if (inBankList != null) {
            mInBankList.addAll(inBankList);
        }
        if (vInBankName.getTag() == null) {
            showBankInfo(mInBankList.get(0), false);
        }
    }

    /**
     * 银行卡变更，重新请求
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(RefreshBankEvent event) {
        if (event != null) {
            mPresenter.selectUrmBankPage();
        }
    }

    @Override
    protected void initImmersionBar() {
        mImmersionBar = ImmersionBar.with(this);
        mImmersionBar.statusBarColorTransformEnable(true)
                .keyboardEnable(true)
                .navigationBarWithKitkatEnable(false)
                .init();
    }

    @Override
    protected boolean hasCommonTitle() {
        return false;
    }

    @Override
    protected boolean hasBindEventBus() {
        return true;
    }

    @Override
    public void setPresenter(QuickPayWebContract.Presenter presenter) {
        this.mPresenter = presenter;
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.onDestroyPresenter();
            mPresenter = null;
        }
    }
}
